package com.example.controller;

import com.example.aop.CounterLimitAnno;
import com.example.aop.SlidingLimitAnno;
import com.example.redis.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author syg
 * @description
 * @date 2021/12/27 14:41
 */
@RequestMapping("/api")
@RestController
@Slf4j
public class TestController {

    @Autowired
    DistributedLock lock;



    @PostMapping("/distributedLock")
    @ResponseBody
    public String distributedLock(String key, String uuid, String secondsToLock, String userId) throws Exception{
//        String uuid = UUID.randomUUID().toString();
        Boolean locked = false;
        try {
            locked = lock.distributedLock(key, uuid, secondsToLock);
            if(locked) {
                log.info("userId:{} is locked - uuid:{}", userId, uuid);
                log.info("do business logic");
//                TimeUnit.MICROSECONDS.sleep(10000);
            } else {
                log.info("userId:{} is not locked - uuid:{}", userId, uuid);
            }
        } catch (Exception e) {
            log.error("error", e);
        } finally {
            if(locked) {
                lock.distributedUnlock(key, uuid);
            }
        }

        return "ok";
    }

    @PostMapping("/distributedLimit1")
    @ResponseBody
    @CounterLimitAnno(limitKey="counter", limit = 10)
    public String distributedLimit1(String userId) {
        log.info(userId);
        return "ok";
    }

    @PostMapping("/distributedLimit2")
    @ResponseBody
    @SlidingLimitAnno(limitKey="sliding", timeWin = 10, maxCount = 5)
    public String distributedLimit2(String userId) {
        log.info(userId);
        return "ok";
    }

}
